-
Notifications
You must be signed in to change notification settings - Fork 0
/
Doubly Circular Linked List - Insert node to a specific position.cpp
87 lines (82 loc) · 2.07 KB
/
Doubly Circular Linked List - Insert node to a specific position.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
using namespace std;
struct NODE {
int data;
NODE *prev;
NODE *next;
};
NODE *head, *tail, *prevnode, *temp;
void add(int value){
if(head == NULL){
head = tail = new NODE;
head->data = value;
head->prev = head->next = tail;
} else {
prevnode = tail;
tail->next = head->prev = new NODE;
tail = tail->next;
tail->prev = prevnode;
tail->data = value;
tail->next = head;
}
}
void addTo(int position, int value){
temp = head;
if(position >= 1){
for(int i = 1; i < position-1; i++){
temp = temp->next; // point to position immediate previous node
if(temp == head){
temp = 0;
break;
}
}
if(temp || position == 1){
NODE *newnode = new NODE;
newnode->data = value;
if(position == 1){
head->prev = newnode;
newnode->next = head;
head = newnode;
if(head->next == 0) tail = head;
tail->next = head;
head->prev = tail;
} else {
newnode->prev = temp;
newnode->next = temp->next;
temp->next = newnode;
if(newnode->next == head){
tail = head->prev = newnode;
tail->next = head;
} else {
newnode->next->prev = newnode;
}
}
}
}
if(position < 1 || temp == 0){
cout << "Data not inserted. Invalid position [" << position <<"]." << endl;
}
}
int print(NODE *ref){
if(ref == 0){
cout << "[EMPTY LIST]" << endl;
return false;
} else {
do {
cout << ref->data;
ref = ref->next;
if(ref != head) cout << " => ";
} while(ref != head);
cout << endl;
return true;
}
}
int main(){
add(10);
add(20);
add(30);
addTo(1, 5);
addTo(3, 15);
addTo(6, 35);
print(head);
}